<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";

import { appCategory, appProductQuery } from "@/services/goods";

const showSelect = ref("");

if (uni.getStorageSync("selectShopType")) {
  showSelect.value = uni.getStorageSync("selectShopType");
}
// import tabbarView from "../components/tabbar.vue";
const scrollTop = ref(0);
const statusBarHeight = ref(0);
// #ifdef APP-PLUS
statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight;

// #endif

const upper = (e) => {
  // console.log(e);
};
const lower = (e) => {
  // console.log(e);
};
const scroll = (e) => {
  // console.log(e);
  // scrollTop.value = e.detail.scrollTop;
};
const scrollLeft = () => {
  newCategoryList.value.forEach((item3, index3) => {
    item3.children.forEach((item2, index2) => {
      item2.select = false;

      //  else {
      //   item2.select = false;
      // }
    });
  });
};
const searchFun = () => {
  console.log("搜索");
  uni.navigateTo({
    url: "/pages/goods/goods_search/index",
  });
};
const scanFun = () => {
  console.log("扫码");
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index?type=goods" });
  // #endif
  // #ifdef APP-PLUS
  // 允许从相机和相册扫码
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    // autoZoom: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);

      uni.navigateTo({
        url: "/pages/goods/goods_search/index?code=" + res.result,
      });
    },
  });
  // #endif
};
// onMounted(() => {

// });
const screenHeight = ref(0);
const type = ref("");
onLoad((e) => {
  type.value = e.type ? e.type : "";
});
onShow(() => {
  if (newCategoryList.value.length > 0) {
    getAppProductQuery(1);
  } else {
    getAppCategory();
  }

  uni.getSystemInfo({
    success: (res) => {
      const screenWidth = res.windowWidth; // 屏幕宽度，单位为px
      screenHeight.value = res.windowHeight; // 屏幕高度，单位为px
    },
  });
});

//商品分类
const categoryList = ref([]);
const newCategoryList = ref([]);

const getAppCategory = async () => {
  try {
    let res = await appCategory();
    // categoryList.value = res.data;
    // form.value.categoryId = res.data[0].id;
    getAppProductQuery(1);
    let arr = [];
    let newArr = [];
    let newArr2 = [];

    res.data.forEach((item, index) => {
      if (!item.parentId) {
        arr.push({ ...item, select: false, children: [] });
      } else {
        newArr.push({ ...item });
      }
    });
    arr.forEach((item, index) => {
      newArr.forEach((item2, index2) => {
        if (item.id == item2.parentId) {
          // item2.children = item.children || [];

          item.children.push({ ...item2, select: false, children: [] });
          newArr.splice(index2, 1);
        }
      });
    });
    arr.forEach((item, index) => {
      item.children.forEach((element, index) => {
        newArr.forEach((item2, index2) => {
          if (element.id == item2.parentId) {
            element.children.push({
              ...item2,
              select: false,
              text: item2.name,
            });
          }
        });
      });
    });
    console.log(arr);
    newCategoryList.value = arr;
    // newCategoryList.value = [];
  } catch (e) {}
};
const selectLive = ref(1);
const tagObj = ref({ X: 0, Y: 0 });
const selectOne = ref(-1);
const selectTwo = ref(-1);
const selectThree = ref(0);
const toSelect = ref(false);
const clickItem = (item, index, num, e, el) => {
  console.log(e);
  if (toSelect.value) {
    return;
  }
  toSelect.value = true;
  if (index != 2) {
    newCategoryList.value.forEach((item3, index3) => {
      item3.children.forEach((item2, index2) => {
        item2.select = false;
      });
    });
  }
  selectLive.value = index;
  if (index == 1) {
    selectName.value = item.name;
    if (!item.id) {
      selectOne.value = 0;
      // if (
      //   newCategoryList.value[selectOne.value - 1].children[selectTwo.value]
      // ) {
      //   newCategoryList.value[selectOne.value - 1].children[
      //     selectTwo.value
      //   ].select = false;
      // }
    } else {
      selectOne.value = num;
    }
  }
  if (index == 2) {
    selectNameTwo.value = item.name;
    let isshows = true;

    newCategoryList.value.forEach((item3, index3) => {
      item3.children.forEach((item2, index2) => {
        if (item2.id != item.id) {
          item2.select = false;
          isshows = false;
        }
        //  else {
        //   item2.select = false;
        // }
      });
    });
    item.select = !item.select;
    // if (isshows) {
    //   item.select = !item.select;
    // }

    selectTwo.value = num;
  }
  if (index == 3) {
    console.log("item", selectOne.value, selectTwo.value);
    selectNameThree.value = item.name;
    item.select = false;
    selectThree.value = num;
  }
  if (e) {
    tagObj.value = {
      X: e.detail.x,
      Y: e.detail.y,
    };
  }

  console.log("tagObj.value", tagObj.value);

  toSelect.value = false;
  if (form.value.categoryId == item.id) {
    return;
  }
  form.value.categoryId = item.id;
  getAppProductQuery(1);
};

const lowerto = (e) => {
  getAppProductQuery();
};
//获取商品
const form = ref({
  categoryId: "",
  pageIndex: 1,
  pageSize: 20,
  barCode: "",
  code: "",
  name: "",
  skuCode: "",
  categoryId: "",
  available: "",
  hasOfferPrice: true,
});
console.log(form.value);
const productData = ref([]);
const loading = ref(true);

const getAppProductQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
  }
  if (index) {
    form.value.pageIndex = index;
  }
  loading.value = true;

  try {
    let res = await appProductQuery(form.value);
    if (res.code == 200) {
      productData.value = productData.value.concat(res.data.datas);

      console.log(productData.value);
      form.value.pageIndex = form.value.pageIndex + 1;
      loading.value = false;
    } else {
    }

    console.log(res);
  } catch (e) {}
};

//编辑商品
const goEdt = (item) => {
  uni.navigateTo({ url: "/pages/supplier/det/index?id=" + item.id });
};

//商品分类
const selectName = ref("全部商品");
const selectNameTwo = ref("");
const selectNameThree = ref("");
const oneSelectIndex = ref("");
const themeVarsCollapse = reactive({
  collapseItemContentFontSize: "24rpx",
  cellFontSize: "24rpx",
  // cellVerticalPadding: "0rpx",
  cellHorizontalPadding: "10rpx",
  collapseItemContentPadding: "0rpx",
  collapseItemContentBackground: "#ededed",
});

const actions = ref([
  { text: "选项一" },
  { text: "选项二" },
  { text: "选项三" },
]);
const showPopover = ref(false);
const activeName = ref("1");
const onCollapseChange = (name) => {
  console.log("SDASASD", name);
  setTimeout(() => {
    activeName.value = name;
  }, 100);
};
const open = (e) => {
  console.log("open", e);
};

// 定义 close 方法
const close = (e) => {
  console.log("close", e);
};

const cell = ref(false);
// 定义 change 方法
const change = (e) => {
  let newId = form.value.categoryId;
  toSelect.value = true;

  selectLive.value = 1;

  newCategoryList.value.forEach((item, index) => {
    item.children.forEach((item2, index2) => {
      item2.select = false;
    });
  });
  let isSelect = false;

  e.forEach((item, index) => {
    if (item.status == "open") {
      isSelect = true;
      // #ifdef APP-PLUS

      selectOne.value = index;
      // #endif
      // #ifdef H5

      selectOne.value = index - 1;
      // #endif
      if (item.name == 0) {
        selectOne.value = index - 1;
        form.value.categoryId = "";
        selectName.value = "全部商品";
      } else {
        form.value.categoryId = newCategoryList.value[item.name - 1]
          ? newCategoryList.value[item.name - 1].id
          : "";
        selectName.value = newCategoryList.value[item.name - 1]
          ? newCategoryList.value[item.name - 1].name
          : "";
      }
    }
  });
  if (isSelect) {
    cell.value = true;
  } else {
    selectOne.value = -1;
    cell.value = false;
  }
  toSelect.value = false;
  if (newId == form.value.categoryId) {
    return;
  }
  selectTwo.value = -1;
  getAppProductQuery(1);
};
const cateId = ref("");
const cateList = ref([
  {
    id: "1",
    name: "分类1",
  },
  {
    id: "2",
    name: "分类2",
  },
  {
    id: "3",
    name: "分类4",
  },
]);

// 方法
const selectItem = (item) => {
  console.log(item);
};
const closeshow = () => {
  newCategoryList.value.forEach((item, index) => {
    item.children.forEach((item2, index2) => {
      item2.select = false;
    });
  });
};

const goadd = () => {
  uni.navigateTo({
    url: "/pages/goods/goods_add/index?type=add",
  });
};
const getSearchFun = () => {
  uni.navigateTo({
    url: "/pages/supplier/list_search/index",
  });
};

//无网状态
const connected = () => {
  if (newCategoryList.value.length > 0) {
    getAppProductQuery(1);
  } else {
    getAppCategory();
  }
};
</script>

<template>
  <view @click="closeshow">
    <topNav :title="'供应商商品库'" rType="customize" :clickable="false">
      <template #right>
        <view>
          <up-icon
            @click="getSearchFun"
            name="search"
            color="#1D2129"
            size="50rpx"
          ></up-icon>
        </view> </template
    ></topNav>
    <view
      class="goods_form"
      :style="'height: calc(100vh - ' + (statusBarHeight + 'px') + ' - 88rpx)'"
    >
      <view class="goods_left">
        <scroll-view
          :style="
            'height: calc(100vh - ' + (statusBarHeight + 'px') + ' - 88rpx)'
          "
          :scroll-top="scrollTop"
          scroll-y="true"
          class="scroll-Y"
          @scrolltoupper="upper"
          @scrolltolower="lower"
          @scroll="scrollLeft"
        >
          <!-- :class="item.id == form.categoryId ? 'select-item' : ''" -->
          <!-- <view
          class="scroll-view-item scroll-view-item2"
          @click="clickItem({ id: '', name: '全部商品' }, 1)"
        >
          全部商品</view
        > -->
          <up-collapse
            :accordion="true"
            @change="change"
            @close="close"
            @open="open"
          >
            <up-collapse-item
              :name="0"
              @click.stop="clickItem(item, 1, index)"
              :class="selectOne == 0 ? 'select-item__to1' : ''"
            >
              <template #title>
                <view
                  :class="
                    -1 == selectOne ? 'u-page__item__title__slot-title' : ''
                  "
                  >{{ "全部商品" }}</view
                >
              </template>
            </up-collapse-item>
            <!-- :title="item.name"
            :name="item.id" -->
            <up-collapse-item
              v-for="(item, index) in newCategoryList"
              :key="index"
              :name="index + 1"
              :class="
                (selectOne == index && selectTwo == 0 && cell
                  ? 'select-item__to2'
                  : selectOne == index && selectTwo != 0 && cell
                  ? 'select-item__to2no'
                  : '') +
                ' ' +
                (selectOne == index ? 'select-item__to1' : '')
              "
              @click.stop="clickItem(item, 1, index)"
            >
              <template #title>
                <view
                  :class="
                    selectOne == index ? 'u-page__item__title__slot-title' : ''
                  "
                  >{{ item.name }}</view
                >
              </template>
              <view
                class="list-itemTwo"
                :class="
                  selectOne == index && selectTwo == indexTwo
                    ? 'sel-list-itemTwo'
                    : ''
                "
                v-for="(itemTwo, indexTwo) in item.children"
                :key="indexTwo"
                @click.stop="clickItem(itemTwo, 2, indexTwo, $event, $el)"
              >
                {{ itemTwo.name }}

                <view
                  @click.stop
                  v-if="itemTwo.select"
                  class="list-itemThree"
                  :style="
                    newCategoryList.length - index > 5
                      ? 'left: calc( 150rpx );top: ' + (tagObj.Y - 15) + 'px; '
                      : 'left:calc(150rpx ) ;bottom: calc( ' +
                        screenHeight +
                        'px' +
                        ' - ' +
                        (tagObj.Y + 15) +
                        'px ); '
                  "
                >
                  <view
                    class="item_arrow"
                    :style="
                      newCategoryList.length - index > 5
                        ? 'top: ' + 15 + 'px; '
                        : 'bottom: calc( ' + 15 + 'px ); '
                    "
                  ></view>
                  <view
                    @click.stop="clickItem(itemThree, 3, indexThree)"
                    v-for="(itemThree, indexThree) in itemTwo.children"
                    :key="indexThree"
                    >{{ itemThree.name }}</view
                  >
                </view>
              </view>
            </up-collapse-item>
          </up-collapse>

          <view style="width: 100%; height: 300rpx"></view>
        </scroll-view>
      </view>

      <view class="goods_right">
        <scroll-view
          :style="
            'height: calc(100vh - ' + (statusBarHeight + 'px') + ' - 88rpx)'
          "
          :scroll-top="scrollTop"
          scroll-y="true"
          class="scroll-R"
          @scrolltoupper="upper"
          @scrolltolower="lowerto"
          @scroll="scroll"
        >
          <view class="select-titles">
            {{ selectLive >= 1 ? selectName : "" }}
            {{ selectLive >= 2 ? ">" + selectNameTwo : ""
            }}{{ selectLive >= 3 ? ">" + selectNameThree : "" }}</view
          >
          <!-- <view>
          <up-select
            v-model:current="cateId"
            label="分类"
            :options="cateList"
            @select="selectItem"
          ></up-select>
        </view> -->

          <view
            class="scroll-Y-item"
            v-for="(item, index) in productData"
            :key="index"
            @click="goEdt(item)"
          >
            <view class="scroll-item-left">
              <image :src="item.image" mode="scaleToFill" />
            </view>
            <view class="scroll-item-right">
              <view class="goods-item-title">
                <text>{{ item.name }}</text>
              </view>
              <view
                class="goods-item-spec"
                v-if="item.barCodeList && item.barCodeList.length > 0"
              >
                商品码:{{ item.barCodeList ? item.barCodeList[0] : "" }}
              </view>
              <view class="goods-item-spec" v-if="item.dhCode">
                称码:{{ item.dhCode ? item.dhCode : "" }}
              </view>
              <view class="goods-item-price">
                ¥{{ item.salePrice }}
                {{ item.unit ? "/" + item.unit : "" }}</view
              >
            </view>
          </view>

          <view class="noData" v-if="productData.length <= 0 && !loading">
            <view class="noData-img">
              <image src="@/static/nodate/datas.png" mode="scaleToFill" />
              <view>暂无商品</view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
